import React from 'react';
import type { UploadFile, UploadProps } from 'antd';
import { Button, Upload, Divider, Spin } from 'antd';
import { StarOutlined } from '@ant-design/icons';
import Loading from '@/components/Loading';
import Message from '@/utils/message';
import store from '@/store';
import useSyncState from '../hooks/useSyncState';
import styled from '@emotion/styled';
import { uploadFile } from '@/utils/upload';
import { useTranslation } from 'react-i18next';
import AgentServer from '@/modules/Agent';
import FileSelect from './FileSelect';
import PreviewUrl from './PreviewUrl';

interface ISendPDF {
	onChangeSendPDF?: (e: any) => void;
	errorMessage?: string;
	setErrorMessage?: (message: string) => void;
	pdfStatus: UploadStatus;
	setPdfStatus: (pdfStatus: UploadStatus) => void;
	tips?: string;
}

enum UploadStatus {
	IDLE = 'IDLE',
	DONE = 'DONE',
	FAILED = 'FAILED',
	SUCCESS = 'SUCCESS',
	PROGRESS = 'PROGRESS'
}

const IconSvg = styled.svg`
	width: 14px;
	height: 16px;
`;

const LoadingButton = styled(Button)`
	display: flex;
	align-items: center;
	justify-content: space-between;
	background-color: #fff;
`;

const SendPDF = (props: ISendPDF) => {
	const { t } = useTranslation();
	const { onChangeSendPDF, errorMessage = '', setErrorMessage, pdfStatus, setPdfStatus, tips = '' } = props;
	const [status, setStatus] = useSyncState<UploadStatus>(UploadStatus.IDLE);
	const [fileList, setFileList] = useSyncState<UploadFile[]>([]);
	const [selectedFile, setSelectedFile] = useSyncState<{ id: number; name: string; url: string } | null>(null);
	const uploadProps: UploadProps = {
		name: 'file',
		iconRender: (file, listType) => {
			if (pdfStatus === UploadStatus.DONE || pdfStatus === UploadStatus.PROGRESS) {
				return (
					<IconSvg className="widget-icon" aria-hidden="true">
						<use xlinkHref={'#icon-widget-a-bianzu6'}></use>
					</IconSvg>
				);
			} else {
				return <></>;
			}
		},
		fileList: [],
		customRequest: async (request: any) => {
			setPdfStatus(UploadStatus.IDLE);
			setErrorMessage && setErrorMessage('');
			onChangeSendPDF && onChangeSendPDF(null);
			if (request.file.type !== 'application/pdf') {
				Message.warning(t('upload-pdf-file'));
				return;
			}

			if (request.file.size > AgentServer.configure.maxUploadFileSize) {
				if (fileList().length === 0) {
					setPdfStatus(UploadStatus.IDLE);
				} else {
					setPdfStatus(UploadStatus.DONE);
				}
				fileList().length !== 0 && fileList()[0].response && onChangeSendPDF && onChangeSendPDF(fileList()[0].response);
				Message.warning(t('upload-file-less-than-50m'));
				return;
			}
			setPdfStatus(UploadStatus.PROGRESS);

			try {
				const data = await uploadFile(request.file);
				if (data) {
					setPdfStatus(UploadStatus.DONE);
					setFileList([
						{
							uid: new Date().getTime().toString(),
							name: data?.name || '',
							status: 'done',
							response: data, // custom error message to show
							url: AgentServer.configure.replaceStaticUrl(data.url) || ''
						}
					]);
				} else {
					Message.warning(t('upload-failed'));
					setPdfStatus(UploadStatus.FAILED);
					setFileList([]);
				}
				onChangeSendPDF && onChangeSendPDF(data);
			} catch (error) {
				setPdfStatus(UploadStatus.FAILED);
				Message.warning(t('upload-failed'));
				uploadProps.fileList = [];
				console.log(error);
			}
		},
		onChange(info) {
			if (info.file.status !== 'uploading') {
				console.log(info.file, info.fileList);
			}
			if (info.file.status === 'done') {
			} else if (info.file.status === 'error') {
			}
		},

		accept: '.pdf',
		maxCount: 1,

		showUploadList: {
			showRemoveIcon: false,
			previewIcon: <StarOutlined />
		}
	};

	const getButtonText = () => {
		if (pdfStatus === UploadStatus.IDLE) return <Button style={{ backgroundColor: '#fff' }}>{t('to-upload-pdf')}</Button>;
		if (pdfStatus === UploadStatus.PROGRESS)
			return (
				<LoadingButton>
					<Loading width={16} height={16} />
					{t('pdf-uploading')}
				</LoadingButton>
			);
		if (pdfStatus === UploadStatus.DONE || pdfStatus === UploadStatus.FAILED) return <Button style={{ backgroundColor: '#fff' }}>重新上传PDF</Button>;
	};

	const selectChange = (value: number) => {
		const file = AgentServer.getAllPdffiles().find(item => item.id === value);
		if (file) {
			setSelectedFile(file);
			onChangeSendPDF && onChangeSendPDF(file);
		}

		console.log(value);
	};

	return (
		<div className="widget-pdf-upload" style={{ pointerEvents: pdfStatus === UploadStatus.PROGRESS ? 'none' : '' }}>
			{/* <p>{tips}</p>
			<Upload {...uploadProps} disabled={selectedFile() !== null} fileList={fileList()} className={selectedFile() ? 'command-disabled' : ''}>
				{getButtonText()}
			</Upload> */}

			<FileSelect disabled={fileList().length !== 0} options={AgentServer.getAllPdffiles()} placeholder={t('select-pdf-placeholder') || ''} changeHandler={selectChange} />
			{errorMessage && pdfStatus !== UploadStatus.DONE ? <p className="error-message">{errorMessage}</p> : undefined}
			<PreviewUrl url={selectedFile()?.url || ''}></PreviewUrl>
		</div>
	);
};

export default SendPDF;
